#!/usr/bin/perl -w
####################################################
# Copyright (c) 2002-2007 BioWare Corp.
# http://www.bigdaddymonitor.org
#
# This file is part of the BigDaddy Monitoring
# program. It is free software distributed under
# the terms of the BSD License. It is ditributed
# in the hopes that it will be useful, but
# WITHOUT ANY WARRANTY; without event the implied
# warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
# The BSD License is available from:
# http://www.opensource.org/licenses/bsd-license.php
####################################################
#=============================================================================#
#BigDaddy Module: SNMP Network Usage
#Author: Craig Miller
#Date: 20.10.2006
#=============================================================================#

=intro

=cut

use strict;
use POSIX qw(ceil);
my ($sServer, $sInterface, $sDirection) = @ARGV;

my @aResults;

my $sFilename="/tmp/bigdaddy.network.".$sServer.".".$sInterface.".".$sDirection;
my $nCurrentTimeStamp=time();

my $nCurrentOctets;
my $nPreviousTimeStamp;
my $nPreviousOctets;
my $nBitsPerSecond;

if (lc($sDirection) eq lc("IN"))
{
    @aResults=`snmpwalk -c public -v 1 $sServer IF-MIB::ifInOctets.$sInterface`;

    foreach my $sLine (@aResults)
    {
        
        if ($sLine =~ m/IF-MIB::ifInOctets.[0-9]+ = Counter32: ([0-9]+)/i)
        {
            $nCurrentOctets=$1;
        }
    }
}
else
{
    @aResults=`snmpwalk -c public -v 1 $sServer IF-MIB::ifOutOctets.$sInterface`;

    foreach my $sLine (@aResults)
    {
        
        if ($sLine =~ m/IF-MIB::ifOutOctets.[0-9]+ = Counter32: ([0-9]+)/i)
        {
            $nCurrentOctets=$1;
        }
    }
}

$nPreviousTimeStamp=0;
$nPreviousOctets=0;

# Read File

if (open(FILE, "< $sFilename"))
{

    $nPreviousTimeStamp=<FILE>;
    $nPreviousOctets=<FILE>;

    close(FILE);
}


# Write File

if (open(FILE, "> $sFilename"))
{
    print FILE $nCurrentTimeStamp."\n";
    print FILE $nCurrentOctets."\n";

    close(FILE);
}

if ($nCurrentOctets <= $nPreviousOctets)
{
    $nPreviousOctets=$nPreviousOctets-4294967296;
}

$nBitsPerSecond=ceil(($nCurrentOctets-$nPreviousOctets)/($nCurrentTimeStamp-$nPreviousTimeStamp)*8);


print $nBitsPerSecond;

